package com.elangzhi.ssm.modules.demand.app;

import com.alibaba.fastjson.JSONObject;
import com.elangzhi.ssm.controller.json.Tip;
import com.elangzhi.ssm.model.Demand;
import com.elangzhi.ssm.model.GoodsComment;
import com.elangzhi.ssm.model.Image;
import com.elangzhi.ssm.model.User;
import com.elangzhi.ssm.modules.demand.services.DemandService;
import com.elangzhi.ssm.modules.goodsComment.services.GoodsCommentService;
import com.elangzhi.ssm.modules.image.services.ImageService;
import com.elangzhi.ssm.modules.user.services.ThinksService;
import com.elangzhi.ssm.modules.user.services.UserService;
import com.elangzhi.ssm.tools.UUIDFactory;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.stream.events.Comment;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
* 需求 客户端 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/demand")
public class AppDemandController {

    /**
     * 支付
     * @param id 需求id
     * @return 成功状态
     */
    @RequestMapping("/pay")
    @ResponseBody
    public Tip pay(Long id){
        Demand demand = demandService.selectById(id);
        User user1 = userService.selectById(demand.getSendUserId());
        User user2 = userService.selectById(demand.getReceiveUserId());
        JSONObject jsonObject = thinksService.zhuanzhang(user1.getThinksId(),user2.getThinksId(),demand.getPrice().toString());
        if(!jsonObject.getBoolean("state")){
            return new Tip(2);
        }

        demand.setStatus(3);
        try {
            demandService.updateById(demand);
            return new Tip();
        } catch (Exception e) {
            System.out.println("支付成功");
            return new Tip(1);
        }
    }

    /**
     * 支付完成
     * @param goodsComment 评价内容
     *                     {
     *                     userId 用户id
     *                     goodsId 被评价用户id
     *                     tags 需求id
     *                     content 内容
     *                     score 评分
     *                     }
     * @return 成功状态
     */
    @RequestMapping("/demandComment")
    @ResponseBody
    public Tip demandComment(GoodsComment goodsComment){
        if(goodsComment != null){

            try {
                goodsComment.setId(UUIDFactory.getLongId());
                goodsComment.setType(2);
                goodsComment.setSetTime(new Date());
                goodsCommentService.insert(goodsComment);

                Demand demand = demandService.selectById(Long.valueOf(goodsComment.getTags()));
                demand.setStatus(demand.getStatus()+1);
                demandService.updateById(demand);

                return new Tip(goodsComment);
            } catch (Exception e) {
                System.out.println("评价承接人失败");
                return new Tip(2);
            }
        }else{
            return new Tip(1);
        }
    }

    /**
     * 获取针对指定人的评论 分页
     * @param userId 商品ID
     * @param page 当前页
     * @param size 每页大小
     * @return 评论列表
     */
    @RequestMapping("listUserCommentByUserId")
    @ResponseBody
    public PageInfo<GoodsComment> listUserCommentByUserId(
            @RequestParam("userId") Long userId,
            @RequestParam("page") Integer page,
            @RequestParam("size")  Integer size){
        return goodsCommentService.listByGoodsId(userId,page,size);
    }

    /**
     * 承接需求
     * @param id 需求id
     * @param receiveUserId 承接人id
     * @return 成功状态
     */
    @RequestMapping("/receive")
    @ResponseBody
    public Tip receive(Long id,Long receiveUserId){
        Demand demand = demandService.selectById(id);
        demand.setReceiveTime(new Date());
        demand.setReceiveUserId(receiveUserId);
        demand.setStatus(2);
        try {
            demandService.updateById(demand);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("承接失败");
            return new Tip(1);
        }
    }

    /**
     * 修改需求
     * @param demand 实体参数
     * @return 成功状态
     */
    @RequestMapping("/update")
    @ResponseBody
    public Tip update(Demand demand, @RequestParam(required = false) MultipartFile[] files, HttpServletRequest request){
        Demand old = demandService.selectById(demand.getId());
        demand.setStatus(old.getStatus());
        try {
            if(demand.getStatus() == 1){
                demandService.updateById(demand);
                saveImg(demand.getId(),files,request);
                return new Tip();
            }else{
                return new Tip(2);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 发布需求
     * @param demand 实体参数
     * @return 成功状态
     */
    @RequestMapping("/save")
    @ResponseBody
    public Tip save(Demand demand, @RequestParam(required = false)  MultipartFile[] files, HttpServletRequest request){
        demand.setId(UUIDFactory.getLongId());
        demand.setSetTime(new Date());
        demand.setStatus(1);
        try {
            demandService.insert(demand);
            saveImg(demand.getId(),files,request);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 保存图片
     * @param demandId 需求id
     * @param files 需求图片
     */
    public void saveImg(Long demandId,MultipartFile[] files,HttpServletRequest request){
        if (files != null) {
            try {
                for(MultipartFile file : files){
                    String fileName = file.getOriginalFilename();
                    String saveName = UUIDFactory.getLongId() + fileName.substring(fileName.lastIndexOf("."));
                    String url = "/images/demand/" + saveName;
                    String realPath = request.getServletContext().getRealPath(url);
                    file.transferTo(new File(realPath));

                    Image image = new Image();
                    image.setId(UUIDFactory.getLongId());
                    image.setInfo(demandId);
                    image.setType(3);
                    image.setUrl(url);
                    imageService.insert(image);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 删除图片
     * @param id 图片id
     * @return 删除状态
     */
    @RequestMapping("/deleteImg")
    @ResponseBody
    public Tip deleteImg(Long id){
        try {
            imageService.deleteById(id);
            return new Tip();
        } catch (Exception e) {
            System.out.println("删除图片失败");
            return new Tip(1);
        }
    }


    /**
     * 获取需求列表 传省市区参数
     * @param demand 参数
     * @param page 第几页
     * @param size 每页大小
     * @return 列表
     */
    @RequestMapping("/listByRegion")
    @ResponseBody
    public PageInfo<Demand> listByRegion(Demand demand,
                                         @RequestParam Integer page,
                                         @RequestParam Integer size){
        PageInfo<Demand> demands = demandService.listByRegion(demand,page,size);
        for(Demand d : demands.getList()){
            d.setBannerList(imageService.listByTypeInfo(3,d.getId()));
            d.setSendUser(userService.selectById(d.getSendUserId()));
        }
        return demands;
    }

    /**
     * 获取我发布的
     * @param sendUserId 发布者id
     * @param page 第几页
     * @param size 每页大小
     * @return 列表
     */
    @RequestMapping("/listBySend")
    @ResponseBody
    public PageInfo<Demand> listBySend(
                                         @RequestParam Long sendUserId,
                                         @RequestParam Integer page,
                                         @RequestParam Integer size){
        PageInfo<Demand> demands = demandService.listBySend(sendUserId,page,size);
        for(Demand d : demands.getList()){
            d.setBannerList(imageService.listByTypeInfo(3,d.getId()));
            d.setSendUser(userService.selectById(d.getSendUserId()));
            if(d.getReceiveUserId() != null){
                d.setReceiveUser(userService.selectById(d.getReceiveUserId()));
            }
        }
        return demands;
    }

    /**
     * 获取我发布的
     * @param receiveUserId 发布者id
     * @param page 第几页
     * @param size 每页大小
     * @return 列表
     */
    @RequestMapping("/listByReceive")
    @ResponseBody
    public PageInfo<Demand> listByReceive(
            @RequestParam Long receiveUserId,
            @RequestParam Integer page,
            @RequestParam Integer size){
        PageInfo<Demand> demands = demandService.listByReceive(receiveUserId,page,size);
        for(Demand d : demands.getList()){
            d.setBannerList(imageService.listByTypeInfo(3,d.getId()));
            d.setSendUser(userService.selectById(d.getSendUserId()));
            d.setReceiveUser(userService.selectById(d.getReceiveUserId()));
        }
        return demands;
    }

    /**
     * 获取需求详情
     * @param id 需求id
     * @return 需求详情
     */
    @RequestMapping("/findById")
    @ResponseBody
    public Demand findById(Long id){
        Demand demand = demandService.selectById(id);
        demand.setBannerList(imageService.listByTypeInfo(3,id));
        demand.setSendUser(userService.selectById(demand.getSendUserId()));
        if(demand.getReceiveUserId() != null){
            demand.setReceiveUser(userService.selectById(demand.getReceiveUserId()));
        }
        return demand;
    }

    /**
     * 删除需求
     * @param id id
     * @return 成功状态
     */
    @RequestMapping("/deleteById")
    @ResponseBody
    public Tip deleteById(Long id){
        try {
            Demand demand = demandService.selectById(id);
            if(demand.getStatus() != 1){
                return new Tip(2);
            }
            demandService.deleteById(id);
            return new Tip();
        } catch (Exception e) {
            System.out.println("删除需求失败");
            return new Tip(1);
        }
    }




    //---------------------------- property -------------------------------

    @Resource
    private DemandService demandService;

    @Resource
    private ImageService imageService;

    @Resource
    private UserService userService;

    @Resource
    private ThinksService thinksService;

    @Resource
    private GoodsCommentService goodsCommentService;

}
